package com.yf.notify.modules.email.providers.qcloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ses.v20201002.SesClient;
import com.tencentcloudapi.ses.v20201002.models.SendEmailRequest;
import com.tencentcloudapi.ses.v20201002.models.Template;
import com.yf.ability.config.dto.CfgPropDTO;
import com.yf.ability.config.enums.ConfigType;
import com.yf.ability.config.enums.ProviderType;
import com.yf.ability.config.service.CfgPropService;
import com.yf.base.api.exception.ServiceException;
import com.yf.notify.modules.email.providers.qcloud.config.QCloudEmailConfig;
import com.yf.notify.modules.email.service.EmailService;
import com.yf.notify.utils.ArrayUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 腾讯云人脸识别实现
 * @author
 */
@Log4j2
@Service("qcloudEmailService")
public class QCloudEmailServiceImpl implements EmailService {

    @Autowired
    private CfgPropService cfgPropService;

    /**
     * 单次最多50收件人
     */
    public static final int MAX_TO = 50;

    @Override
    public boolean sendMail(String subject, String[] emails, String body, String templateId, LinkedHashMap<String,String> params) throws ServiceException {

        // 获取短信配置
        CfgPropDTO dto = cfgPropService.detail(ConfigType.EMAIL, ProviderType.QCLOUD);
        QCloudEmailConfig conf = JSON.parseObject(dto.getData(), QCloudEmailConfig.class);

        if(conf == null || StringUtils.isBlank(conf.getSecretId()) || StringUtils.isBlank(conf.getSecretKey())){
            throw new ServiceException("邮件发送配置错误，请联系管理员！");
        }

        // 最多50个收件人
        if(emails.length > MAX_TO){
            List<List<String>> list = ArrayUtils.split(emails, MAX_TO);
            boolean result = true;
            for(List<String> item: list){
                String [] subs = item.toArray(new String[0]);
                result = sendMail(conf, subject, subs, body, templateId, params);
                // 出错不发
                if(!result){
                    break;
                }
            }
            return result;
        }else{
            // 直接发送
            return sendMail(conf, subject, emails, body, templateId, params);
        }
    }

    /**
     * 发送邮件
     * @param conf
     * @param subject
     * @param emails
     * @param body
     * @param templateId
     * @param params
     * @return
     * @throws ServiceException
     */
    public boolean sendMail( QCloudEmailConfig conf, String subject, String[] emails, String body, String templateId, LinkedHashMap<String,String> params) throws ServiceException {

        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(conf.getSecretId(), conf.getSecretKey());
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ses.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SesClient client = new SesClient(cred, "ap-hongkong", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendEmailRequest req = new SendEmailRequest();
            req.setFromEmailAddress(conf.getFromEmailAddress());

            // 最多50个
            req.setDestination(emails);
            Template template1 = new Template();
            template1.setTemplateID(Long.parseLong(templateId));
            template1.setTemplateData(JSON.toJSONString(params));
            req.setTemplate(template1);
            req.setSubject(subject);
            // 执行发送，没异常则表示成功
            client.SendEmail(req);
            return true;

        } catch (TencentCloudSDKException e) {
            String msg = e.getMessage();
            throw new ServiceException(msg);
        }
    }
}
